/*
 * @Author: xishanxu
 * @LastEditors  : xisuanxu
 * @LastEditTime : 2020-01-17 17:50:32
 */
import { Reducer } from 'redux';
import { Effect } from 'dva';
// import { stringify } from 'querystring';
import router from 'umi/router';
import {
  getAuthorizations,
  // getCaptcha
} from '@/services/login';
import { getUserInfo } from '@/services/user';
import { setAuthority, removeAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';

export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    // getCaptcha: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const loginMessage = yield call(getAuthorizations, payload);
      const res = {
        ...payload,
        ...loginMessage,
      };
      // 存入token
      setAuthority(res, 'adminToken');
      yield put({
        type: 'changeLoginStatus',
        payload: res,
      });
      // 登录成功 获取 用户信息和 做权限管理
      if (loginMessage.status === 'success') {
        const userInfo = yield call(getUserInfo);
        if (userInfo.status === 'success') {
          // TODO:接口字段中还没有这个
          // setAuthority(userInfo.currentAuthority);
          setAuthority('admin');
        }
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }
        router.replace(redirect || '/');
      }
    },

    // *getCaptcha({ payload }, { call }) {
    //   yield call(getCaptcha, payload);
    // },

    logout() {
      removeAuthority('adminToken');
      removeAuthority();
      window.location.reload();
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};

export default Model;
